package com.qqb.service.impl;

import com.qqb.dao.UserDao;
import com.qqb.pojo.User;
import com.qqb.service.UserService;
import com.qqb.util.MD5Util;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;


    @Override
    public void login(User user) throws Exception {

        Example example = Example.builder(User.class)
                .select("account","password")
                .where(Sqls.custom().andEqualTo("account", user.getAccount()))
                .build();
        String s = userDao.selectByExample(example).toString().replace("[","").replace("]","");
        String pwd = MD5Util.string2MD5(user.getPassword());
        String passwd = MD5Util.convertMD5(pwd);
        user.setPassword(passwd);
        if(!s.equals(user.toString())){
            throw new Exception("账号错误");
        }

    }

    @Transactional
    @Override
    public void register(User user) throws Exception {
        Example example = Example.builder(User.class)
                .select("account")
                .where(Sqls.custom().andEqualTo("account", user.getAccount()))
                .build();
        String s1 = userDao.selectByExample(example).toString();
        if(s1!= null&&!"[]".equals(s1)){
            throw new Exception("账号已经注册");
        }else {
            String s = MD5Util.string2MD5(user.getPassword());
            String pwd = MD5Util.convertMD5(s);
            user.setPassword(pwd);
            userDao.insert(user);
        }
    }
}
